<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="personal-head">
    <CommonHead title="查看账号信息"/>
  </header>

  <!--体: 展示用户信息，账号信息和防沉迷信息-->
  <section class="personal-body">

    <van-divider>用户信息</van-divider>
    <van-cell-group inset v-if="user['avatarUrl']">

      <!--单元格项: 标题，启用链接，跳转地址，垂直居中-->
      <van-cell title="用户头像" is-link to="/UploadAvatar" center>
        <!--图片: MinIO代理地址，宽度，高度，圆角-->
        <van-image :src="MINIO_HOST + '/avatar/' + user['avatarUrl']" width="50px" height="50px" radius="10px"/>
      </van-cell>

      <van-cell title="用户昵称" :value="user['nickName']"
                is-link :to="'/UpdateNickName?nickName=' + user['nickName']"/>

      <van-cell title="用户性别" :value="user['gender'] === 2 ? '保密': user['gender'] === 1 ? '男': '女'"
                is-link :to="'/UpdateGender?gender=' + user['gender']"/>

      <van-cell title="用户年龄" :value="user['age']"
                is-link :to="'/UpdateAge?age=' + user['age']"/>

      <van-cell title="手机号码" :value="user['phone']"
                is-link :to="'/UpdatePhone?phone=' + user['phone']"/>

      <van-cell title="个人描述" is-link :to="'/UpdateUserInfo?userInfo=' + user['userInfo']">
        <template #label>{{ user['userInfo'] }}</template>
      </van-cell>

    </van-cell-group>

    <van-divider>账号信息</van-divider>
    <van-cell-group inset>
      <van-cell title="用户账号" :value="user['username']"/>
      <van-cell title="用户密码" value="*******" is-link to="/UpdatePassword"/>
      <van-cell title="创建时间" :value="toDateStr(user['createTime'])"/>
      <van-cell title="修改时间" :value="toDateStr(user['modifyTime'])"/>
    </van-cell-group>

    <van-divider>防沉迷信息</van-divider>
    <van-cell-group inset>
      <van-cell title="真实姓名" :value="user['realName']"/>
      <van-cell title="身份证号" :value="user['idCard']"/>
    </van-cell-group>

    <van-divider>用户积分</van-divider>
    <van-cell-group inset>
      <van-cell title="用户积分" :value="userPoints"/>
    </van-cell-group>

    <!--操作区: 注销用户按钮-->
    <article class="operation">
      <van-button round block size="small" type="danger" @click="deleteUser">注销用户</van-button>
    </article>

    <!--操作区: 退出登录按钮-->
    <article class="operation">
      <van-button round block size="small" type="warning" @click="logout">退出登录</van-button>
    </article>

  </section>

  <!--脚: 引入Foot子组件-->
  <footer class="personal-foot">
    <CommonFoot/>
  </footer>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import CommonFoot from "@/components/CommonFoot";
import {DELETE_PERSONAL, SELECT_PERSONAL, SELECT_POINTS} from '@/api/user';
import {useStore} from "vuex";
import router from "@/router";
import {onBeforeMount, shallowRef} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {MINIO_HOST, SUCCESS, toDateStr} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
const vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 用户数据
let user = shallowRef({});

// data: 用户积分
let userPoints = shallowRef(0);

/* ==================== method ==================== */

// method: 查询个人信息
async function selectPersonal() {
  const result = await SELECT_PERSONAL();
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    user.value = resp.data;
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

// method: 退出登录
async function logout() {

  // 修改登录状态
  await vuex.dispatch('setLoginFlag', false);

  // 清除sessionStorage中的token值
  sessionStorage.removeItem("token");

  // 清除sessionStorage中的userId值
  sessionStorage.removeItem("userId");

  // 提示操作成功
  showSuccessToast('操作成功，请重新登录');

  // 跳转到登录页面
  await router.push('/LoginByAccount')
}

// method: 注销个人账号
async function deleteUser() {

  // 危险操作保护
  if (!confirm("即将注销个人账号，确定吗？")) {
    return false;
  }

  // 调用对应API接口
  const result = await DELETE_PERSONAL(userId);
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast("账号注销成功");
    await logout();
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

// method: 查询用户积分
async function selectPoints() {
  const result = await SELECT_POINTS();
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    userPoints.value = resp.data;
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  } else {
    selectPersonal();
    selectPoints();
  }
});

</script>

<style scoped lang="scss">
.personal-body {
  text-align: left; // 内容居左

  /*操作区*/
  .operation {
    margin: 15px; // 外边距
  }
}
</style>